/*
 * Copyright (c) 2017,重庆阿莫比科技有限公司,All Rights Reserved.
 */
package com.wowocai.btchina.service.impl;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.wowocai.btchina.amazon.SignedRequestsHelper;
import com.wowocai.btchina.entity.AmazonProductAdEntity;
import com.wowocai.btchina.service.AmazonAdsService;

/**
 * <br/>
 * Date: 2017年5月16日 上午11:25:15 <br/>
 * 
 * @Author 刘建成
 * @Version
 */
@Service
@CacheConfig(cacheNames = "cache1d")
public class AmazonAdsServiceImpl implements AmazonAdsService {

    private final static Logger logger = LoggerFactory.getLogger(AmazonAdsServiceImpl.class);

    /**
     * Use one of the following end-points, according to the region you are
     * interested in:
     * 
     * US: ecs.amazonaws.com
     * CA: ecs.amazonaws.ca
     * UK: ecs.amazonaws.co.uk
     * DE: ecs.amazonaws.de
     * FR: ecs.amazonaws.fr
     * JP: ecs.amazonaws.jp
     * CN: webservices.amazon.cn
     * 
     */
    private static final Map<String, String> ENDPOINTS = new HashMap<String, String>();

    static {
        ENDPOINTS.put("US", "ecs.amazonaws.com");
        ENDPOINTS.put("CA", "ecs.amazonaws.ca");
        ENDPOINTS.put("UK", "ecs.amazonaws.co.uk");
        ENDPOINTS.put("DE", "ecs.amazonaws.de");
        ENDPOINTS.put("FR", "ecs.amazonaws.fr");
        ENDPOINTS.put("JP", "ecs.amazonaws.jp");
        ENDPOINTS.put("CN", "webservices.amazon.cn");
    }

    private static final String ENDPOINT_DEFAULT_COUNTRY = "US";

    private static final String ENDPOINT = ENDPOINTS.get(ENDPOINT_DEFAULT_COUNTRY);

    /**
     * Your AWS Access Key ID, as taken from the AWS Your Account page.
     */
    @Value("${aws.access.key_id}")
    private String AWS_ACCESS_KEY_ID = null;

    /**
     * Your AWS Secret Key corresponding to the above ID, as taken from the AWS
     * Your Account page.
     */
    @Value("${aws.secret.key}")
    private String AWS_SECRET_KEY = null;

    /**
     * 
     */
    @Value("${aws.associate.tag}")
    private String ASSOCIATE_TAG = null;

    /**
     * TODO The function of this method is described here - Optional.
     * 
     * @see com.wowocai.btchina.service.AmazonAdsService#getAmazonAds(java.lang.String)
     */
    @Override
    @Cacheable
    public List<AmazonProductAdEntity> getAmazonAds(String key, String countryCode) {

        String url = initRequestUrl(key, countryCode);
        if (url != null) {
            return parseDoc(url);
        }
        return null;
    }

    @Override
    @Cacheable
    public List<AmazonProductAdEntity> getAmazonAds(String key) {
        return getAmazonAds(key, ENDPOINT_DEFAULT_COUNTRY);
    }

    /**
     * 初始化URL
     * <br/>
     * 
     * @author 刘建成
     * @param keys
     * @return
     */
    private String initRequestUrl(String keys, String ccode) {

        String endpoint = ENDPOINTS.get(ccode);
        if (endpoint == null) {
            endpoint = ENDPOINT;
        }
        // Set up the signed requests helper
        SignedRequestsHelper helper;
        try {
            helper = SignedRequestsHelper.getInstance(endpoint, AWS_ACCESS_KEY_ID, AWS_SECRET_KEY);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        String requestUrl = null;
        // String title = null;

        Map<String, String> params = new HashMap<String, String>();
        params.put("Service", "AWSECommerceService");
        params.put("Version", "2013-08-01");
        params.put("AssociateTag", ASSOCIATE_TAG);
        params.put("Operation", "ItemSearch");
        params.put("SearchIndex", "All");
        params.put("Keywords", keys);
        params.put("ResponseGroup", "Images,ItemAttributes,Offers");

        requestUrl = helper.sign(params);
        return requestUrl;
    }

    private List<AmazonProductAdEntity> parseDoc(String requestUrl) {

        List<AmazonProductAdEntity> list = new ArrayList<AmazonProductAdEntity>();
        org.jsoup.nodes.Document document = null;
        try {
            document = Jsoup.parse(new URL(requestUrl), 20000);
        } catch (IOException e) {
            logger.error("请求URL时出错", e);
            return list;

        }
        Elements items = document.select("Item");
        for (Iterator<Element> iterator = items.iterator(); iterator.hasNext();) {
            Element element = iterator.next();
            try {
                String title = getElemetnText(element.select("title"));
                // String image = getElemetnText(element.select("SmallImage>url"));
                String image = getElemetnText(element.select("TinyImage>url"));
                String offers = getElemetnText(element.select("MoreOffersUrl"));
                String link = getElemetnText(element.select("DetailPageURL"));
                String price = getElemetnText(element.select("FormattedPrice"));
                price = price == null ? "$0.00" : price;
                String id = getElemetnText(element.select("ASIN"));
                AmazonProductAdEntity bean = new AmazonProductAdEntity();
                bean.setId(id);
                bean.setTitle(title);
                bean.setImage(image);
                bean.setOffers(offers);
                bean.setLink(link);
                bean.setPrice(price);
                list.add(bean);
            } catch (Exception e) {
                logger.error("解析XML时出错:{}", element.toString());
            }
        }
        return list;
    }

    private String getElemetnText(Elements elements) {
        if (elements == null || elements.size() == 0) {
            return null;
        }
        return elements.get(0).text();
    }

    public static void main(String[] args) throws Exception {

        // File file = new File("G:/data/test.xml");
        // org.jsoup.nodes.Document document = Jsoup.parse(file, "UTF-8");
        // Elements items = document.select("Item");
        //
        // for (Iterator<Element> iterator = items.iterator(); iterator.hasNext();) {
        // Element element = iterator.next();
        // String title = element.select("title").get(0).text();
        // String image = element.select("SmallImage>url").text();
        // String offers = element.select("MoreOffersUrl").get(0).text();
        // String link = element.select("DetailPageURL").get(0).text();
        // String price = element.select("FormattedPrice").get(0).text();
        // String id = element.select("ASIN").get(0).text();
        // }
    }
}
